--[[
	function: 微信公众平台登录
	author: jim_sun
    wiki: 
    api:
    example:
        curl 'URI/user_account/login_by_wechat?openid=xxxxxxxxx' 
        return
        {
            "status":1,
            "errcode":"",
            "msg":"",
            "data":{
                "token":"xxxxxxxxxxxxxxxxx",
                "expire_time":"123343423535" //过期时间戳
            },
        }

]]
local args = ngx.req.get_uri_args()
local user_id = nil
local openid = args.openid
if not common_util.check_args(1, openid) then
    common_util.exit(200, 0, nil, "101", "openid is missing")
end

local sql = "select user_id from tb_user_info where account="..
ngx.quote_sql_str(openid).." and type=0 limit 1"
--local data,bool = connection:query(sql)
local data,bool = common_util.db_query_common(sql,common_config.db_user_info_addr)
if false == bool  then
	--connection:over()
    common_util.exit(200, 0, nil, "500", "mysql is error")
end

if not next(data) then
    --该账户不存在,需要创建微信公共平台账号
    user_id = common_util.create_user_id()
    local sql = "insert into tb_user_info set account="..ngx.quote_sql_str(openid)..",user_id="..user_id..
        ",create_time="..(ngx.now()*1000)..",status=1,type=0"
    --local data,bool = connection:query(sql)
    local data,bool = common_util.db_query_common(sql,common_config.db_user_info_addr)
    if false == bool  then
        --connection:over()
        common_util.exit(200, 0, nil, "500", "mysql is error")
    end
else
    user_id = tonumber(data[1]["user_id"]) or 0
end

local token,expire_time = common_util.get_token(user_id)
if not token or not expire_time then
    common_util.exit(200, 0, nil, "500", "redis is error")
end

common_util.exit(200, 1, {["token"] = token, ["expire_time"] = expire_time }, "", "")


